package com.doraro.platform.common.utils;


import com.vip.vjtools.vjkit.text.Charsets;
import lombok.SneakyThrows;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TransformMysqlToH2 {


    public static void main(String[] args) throws Exception {
        final Path path = Paths.get("E:\\code\\java\\final-project\\platform-api\\src\\main\\resources\\db\\mysql\\V1__INIT.sql");
        mysqlToH2(path, path);
    }

    /**
     * 将navicat 导出的mysql脚本转换成h2格式的脚本
     *
     * @param src  原文件或者目录
     * @param dest 目的文件（存在则覆盖）,如果src是目录，则可以为null
     */
    @SneakyThrows
    private static void mysqlToH2(Path src, Path dest) {
        if (Files.isDirectory(src)) {
            Files.walk(src).filter(path1 -> !Files.isDirectory(path1)).forEach(path -> mysqlToH2(path, path));
        }
        if (!src.toString().endsWith(".sql")) {
            System.out.println(src.getFileName() + " is not a sql file.skip....");
            return;
        }
        String content = new String(Files.readAllBytes(src), Charsets.UTF_8);

        content = "SET MODE MYSQL;\n\n" + content;

        content = content.replaceAll("`", "");
        content = content.replaceAll("COLLATE.*(?=D)", "");
        content = content.replaceAll("CHARACTER SET.*((?=NOT NULL)|(?=D))", "");
        content = content.replaceAll("COMMENT.*'(?=,)", "");
        content = content.replaceAll("\\).*ENGINE.*(?=;)", ")");
        content = content.replaceAll("USING BTREE", "");
        content = content.replaceAll("DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP", " AS CURRENT_TIMESTAMP");

        content = uniqueKey(content);

        System.out.println(content);
        Files.write(dest, content.getBytes());
    }

    /**
     * h2的索引名必须全局唯一
     *
     * @param content sql建表脚本
     * @return 替换索引名为全局唯一
     */
    private static String uniqueKey(String content) {
        int inc = 0;
        Pattern pattern = Pattern.compile("(?<=KEY )(.*?)(?= \\()");
        Matcher matcher = pattern.matcher(content);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group() + inc++);
        }
        matcher.appendTail(sb);
        content = sb.toString();
        return content;
    }
}
